#!/bin/bash

export DEBIAN_FRONTEND=noninteractive
export DEBCONF_NONINTERACTIVE_SEEN=true
export LC_ALL=zh_CN.UTF-8
export LANG=zh_CN.UTF-8
export LANGUAGE=zh_CN:zh

ARCH=arm64
CHIP=""

# 获取参数
for opt in $@; do
    case "$opt" in
        arch*)
            # 指定了CPU架构
            ARCH=$(echo "$opt" | awk -F '=' '{print$2}')
            ;;
        chip*)
            # 指定了芯片名称，也可以通过这个指定工控机的类型
            CHIP=$(echo "$opt" | awk -F '=' '{print$2}')
            ;;
        *) ;;
    esac
done

function umnt_wait()
{
    for i in {1..5}
    do
        # echo "umount $1 . #$i"
        umount $1 &> /dev/null
        sleep 1
        if [ ! -d $1 ]; then 
            break
        else
            if (( $(ls -a $1 | wc -l) == 2)); then
                break
            fi
        fi
    done
}

# 执行自定义操作
CMDPATH=/customs/live
mount -t proc none /proc &> /dev/null
mount -t sysfs sysfs /sys &> /dev/null
mount -t devpts devpts /dev/pts &> /dev/null

cp -arf /customs/includes/* /
cp -arf /customs/includes_arch/$ARCH/$CHIP/* /

if [ ! -f $CMDPATH/scripts.tmp ]; then
    touch $CMDPATH/scripts.tmp
fi

for script in $(ls -v $CMDPATH | grep ".chroot$" | grep -v '^d'); do
    FILE_NAME=$CMDPATH/$script
    OLDMD5=$(cat $CMDPATH/scripts.tmp | grep "^$FILE_NAME" | awk -F ' ' '{print$2}')
	NEWND5=$(md5sum $FILE_NAME | awk -F ' ' '{print$1}')
    
	if [ "$OLDMD5" != "$NEWND5" ]; then 
		chmod +x $FILE_NAME
		$FILE_NAME $@
        if [ -z "$(sed -n "/${FILE_NAME//\//\\/}/p" $CMDPATH/scripts.tmp)" ]; then 
            echo "$FILE_NAME $NEWND5" >> $CMDPATH/scripts.tmp
        else
		    sed -i "/${FILE_NAME//\//\\/}/ s/.*/${FILE_NAME//\//\\/} $NEWND5/" $CMDPATH/scripts.tmp
        fi
	fi
done

# 清理垃圾
echo "I: 清理运行缓存"
apt-get clean
apt-get autoclean

rm -rf /var/log/*
rm -rf /var/backups/*
rm -rf /var/cache/*
rm -rf /var/tmp/*

rm -f /usr/bin/qemu-arm-static
rm -f /etc/resolv.conf
ln -sf /etc/resolv.conf.local /etc/resolv.conf

umnt_wait /proc
umnt_wait /sys
umnt_wait /dev/pts

history -c 
exit
